package com.suyang.syt.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suyang.syt.auth.AuthUtil;
import com.suyang.syt.dao.interfaces.RoleDao;
import com.suyang.syt.dao.interfaces.UserDao;
import com.suyang.syt.dao.interfaces.UserRoleDao;
import com.suyang.syt.model.Role;
import com.suyang.syt.model.User;
import com.suyang.syt.model.UserRole;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.MySessionContext;
import com.suyang.syt.service.interfaces.LoginService;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.util.Md5Util;

@Service
public class LoginServiceImpl implements LoginService {

	@Autowired
	private UserRoleDao userRoleDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;

	@Override
	public AjaxObj updateLogin(String username, String password, HttpSession session) throws Exception {
		long count = userDao.countUsername(username);
		if (count <= 0) {
			return new AjaxObj(0, "该用户帐号不存在！");
		} else if (count > 1) {
			return new AjaxObj(0, "系统中存在多个【" + username + "】用户名，请联系管理员！");
		} else {
			User user = userDao.loadByUsername(username);
			if (user.getStatus() == -1) {
				return new AjaxObj(0, "该用户帐号被停用，请联系管理员！");
			}
			if (user.getPassword().equals(Md5Util.md5(username, password))) {
				longinHandle(user, session);
				return new AjaxObj(1, "登录成功！", user);
			} else {
				return new AjaxObj(0, "用户名或密码错误，请重新登录！");
			}
		}
	}

	@Override
	public void longinHandle(User user, HttpSession session) throws Exception {
		if (user != null) {
			session.setAttribute("loginUser", user);
			MySessionContext.addSession(session);
			List<UserRole> userRoles = userRoleDao.listUserRoles(user.getId());
			List<Role> roles = new ArrayList<Role>();
			for (UserRole userRole : userRoles) {
				Role role = roleDao.load(userRole.getRoleId());
				if (role != null) {
					roles.add(role);
				}
			}
			boolean isAdmin = this.isRole(roles, AuthUtil.ROLE_ADMIN);
			boolean isPXJG = this.isRole(roles, AuthUtil.ROLE_PXJG);
			boolean isJGJS = this.isRole(roles, AuthUtil.ROLE_JGJS);
			session.setAttribute("isAdmin", isAdmin);
			session.setAttribute("isPXJG", isPXJG);
			session.setAttribute("isJGJS", isJGJS);
			if (!isAdmin) {
				session.setAttribute("allActions", getAllActions(session, roles));
			}
		}
	}

	private boolean isRole(List<Role> roles, int type) {
		if (EmptyUtil.isNotEmpty(roles)) {
			for (Role role : roles) {
				if (role.getRoleType() == type) {
					return true;
				}
			}
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	private Set<String> getAllActions(HttpSession session, List<Role> roles) {
		Set<String> actions = new HashSet<String>();
		Map<String, Set<String>> allAuths = (Map<String, Set<String>>) session.getServletContext().getAttribute("allAuths");
		actions.addAll(allAuths.get("base"));
		for (Role role : roles) {
			if (role.getRoleType() != AuthUtil.ROLE_ADMIN) {
				actions.addAll(allAuths.get(AuthUtil.getName(role.getRoleType())));
			}
		}
		return actions;
	}

}
